package com.gack.business.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.gack.business.dao.ContactsDao;
import com.gack.business.dao.StoreCameraDao;
import com.gack.business.model.Conference;
import com.gack.business.model.ConferenceCameras;
import com.gack.business.model.ConferenceRemind;
import com.gack.business.model.ConferenceUser;
import com.gack.business.model.HistoryConference;
import com.gack.business.model.HistoryConferenceUser;
import com.gack.business.model.JoinConference;
import com.gack.business.model.JoinConferenceRecord;
import com.gack.business.model.Message;
import com.gack.business.model.MessagePush;
import com.gack.business.model.MessagePushUser;
import com.gack.business.model.PushSwitch;
import com.gack.business.model.StoreCameras;
import com.gack.business.model.User;
import com.gack.business.repository.ConferenceCamerasRepository;
import com.gack.business.repository.ConferenceRemindRepository;
import com.gack.business.repository.ConferenceRepository;
import com.gack.business.repository.ConferenceUserRepository;
import com.gack.business.repository.HistoryConferenceRepository;
import com.gack.business.repository.HistoryConferenceUserRepository;
import com.gack.business.repository.JoinConferenceRecordRepository;
import com.gack.business.repository.JoinConferenceRepository;
import com.gack.business.repository.MessagePushRepository;
import com.gack.business.repository.MessagePushUserRepository;
import com.gack.business.repository.MessageRepository;
import com.gack.business.repository.PushSwitchRepository;
import com.gack.business.repository.StoreCamerasRepository;
import com.gack.business.repository.UserRepository;
import com.gack.business.vo.ConferenceUserVO;
import com.gack.business.vo.ConferenceVO;
import com.gack.business.vo.UpdateModel;
import com.gack.helper.common.abstractobj.Result;
import com.gack.helper.common.util.JPushRestAPI;
import com.gack.helper.common.util.PackerUtil;
import com.gack.helper.common.util.RandomCharAndCode;
import com.gack.helper.common.util.SendCode;
import com.gack.helper.common.util.WebServiceUtils;
import com.gack.helper.common.vidyo.VidyoConstant;
import com.gack.helper.common.vidyo.VidyoWebServiceAPI;

import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
 public class ConferenceService implements ConferenceServiceInterface {

	@Autowired
	private ConferenceRepository conferenceRepository;
	@Autowired
	private ConferenceUserRepository conferenceUserRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private HistoryConferenceRepository historyConferenceRepository;
	@Autowired
	private HistoryConferenceUserRepository historyConferenceUserRepository;
	@Autowired
	private JoinConferenceRepository joinConferenceRepository;
	@Autowired
	private ConferenceRemindRepository conferenceRemindRepository;
	@Autowired
	private MessageRepository messageRepository; 
	@Autowired
	private PushSwitchRepository pushSwitchRepository;
	@Autowired
	private MessagePushRepository messagePushRepository;
	@Autowired
	private MessagePushUserRepository messagePushUserRepository;
	@Autowired
	private JoinConferenceRecordRepository joinConferenceRecordRepository;
	@Autowired
	private ConferenceCamerasRepository conferenceCamerasRepository; 
	@Autowired
	private StoreCamerasRepository storeCamerasRepository;
	@Autowired
	private StoreCameraDao cameraDao;
	@PersistenceContext
	private EntityManager manager;
	@Autowired
	private ContactsDao contactsDao;
	/**
	 * 
	
	  * @Title: createConference
	
	  * @Description: 创建会议室
	
	  * @param @param name 会议室名称
	  * @param @param topic 会议室主题
	  * @param @param uid 创建者id
	  * @param @param joinId 其他入会者的id数组
	  * @param @param type 会议室类型 1 普通会议，2 通讯录拉会
	  * @param @return
	  * @param @throws Exception    
	
	  * @return Result 
	
	  * @throws
	 */
	@Override
	@Transactional
	public Result createConference(String name, String topic, String uid, String[] joinId, Integer type) throws Exception {
		Result result = new Result();
		if (name == null || "".equals(name)) {
			result.setKey("error");
			result.setValue("会议名称不能为空");
			return result;
		}
		
		Set<String> set = new HashSet<>();
		set.add(uid);
		
		if (joinId != null) {
			set.addAll(Arrays.asList(joinId));
		}
		//邀请的人的数量加起来不能超过40人
		if (set.size() > 40) {
			result.setKey("error");
			result.setValue("会议室人员达到上限");
			return result;
		}

		//会议室类型 正常创建 type为1 俩人拉会 type为2
		if (type == 2) {
			String cid = checkType(uid, joinId[0]);
			if (cid != null) {
				result.setKey("success");
				result.setValue(cid);
				return result;
			}
			// 老版本代码，以防万一，过了下个版本可以删掉
			/*List<ConferenceUser> conferenceUsers = conferenceUserRepository.findByUid(uid);
			for (ConferenceUser conferenceUser : conferenceUsers) {
				Conference conference = conferenceRepository.findOne(conferenceUser.getCid());
				if (conference != null) {
					if (conference.getType() == 2) {
						ConferenceUser conUser = conferenceUserRepository.findByUidAndCid(joinId[0], conference.getId());
						if (conUser != null) {
							result.setKey("success");
							result.setValue(conference.getId());
							return result;
						}
					}
				}
			}*/
		}
		
		//创建会议室
		Conference conference;
//		conference.setConferenceCode(createConferenceCode()); // 创建6～8位 字母数字混合字符串
		// 创建6～8位 字母数字混合字符串 传递给createVidyo，创建vidyo会议室
		conference = createVidyo(createConferenceCode());
		// 如果为空则vidyo会议室创建失败
		if (conference != null) {
			conference.setName(name);
			conference.setTopic(topic);
			conference.setCreateId(uid);
			conference.setPeople_num(1);
			conference.setPeople_all(40); // vidyo买了40的上限
			conference.setManageId(uid);
			conference.setCreateTime(new Date());
			conference.setType(type);
			//保存会议室
			Conference con = conferenceRepository.save(conference);
			
			if (con != null) {
				User user = userRepository.findOne(uid);
				if (user != null) {
					user.setCreate_meeting_num(user.getCreate_meeting_num() + 1);
					userRepository.save(user);
				}
				ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(uid, con.getId());
				if (conferenceUser == null) {
					//保存创建会议室的人
					ConferenceUser conUser = new ConferenceUser();
					conUser.setCid(con.getId());
					conUser.setUid(uid);
					conUser.setLastModifyTime(new Date());
					conferenceUserRepository.save(conUser); 
				}
				// 拉入其他参加会议的人
				addParticipant(con.getId(), joinId, uid);
				result.setKey("success");
				result.setValue(con.getId());
				return result;
			}
		}
		
		result.setKey("error");
		result.setValue("会议室创建失败，请稍后在试");

		return result;
	}

	/**
	 * 
	
	  * @Title: createVidyo
	
	  * @Description: 传入6～8位conferenceCode，创建vidyo会议室
	
	  * @param @param conferenceCode
	  * @param @return
	  * @param @throws Exception    
	
	  * @return Conference 
	
	  * @throws
	 */
	@Override
	public Conference createVidyo(String conferenceCode) throws Exception{
		// 传入生成的conferenceCode
		Map<String, String> elementBody = new HashMap<>();
		elementBody.put("conferenceCode", conferenceCode);
		// 调用创建vidyo会议室的接口
		boolean flag = VidyoWebServiceAPI.addRoom(elementBody);
		// 创建成功
		if (flag) {
			// 利用同一个map，移除旧参数，封装新参数
			elementBody.remove("conferenceCode");
			// 根据会议室名称查询 eg: 会议XXX 
			elementBody.put("query", VidyoConstant.DEFAULT_NAME + conferenceCode);
			// 调用查询vidyo会议室的接口
			String xml = VidyoWebServiceAPI.getRooms(elementBody);
			// 把返回的xml 解析成map 集合
			Map<String, Object> mapResult = VidyoWebServiceAPI.xmlParserMap(xml, VidyoConstant.GET_ROOMS_RESPONSE);
			int total = Integer.parseInt((String)mapResult.get("total"));
			// 如果查询的总数大于0 说明创建成功
			if (total > 0) {
				List<Map<String, String>> listMap = (List<Map<String, String>>)mapResult.get("listReult");
				Map<String, String> vidyoRoom = listMap.get(0);
				Conference conference = new Conference();
				conference.setConferenceCode(conferenceCode);
				conference.setConferenceId(Integer.parseInt(vidyoRoom.get("roomID")));
				conference.setConferencePin(vidyoRoom.get("roomPIN"));
				conference.setConferenceUrl(vidyoRoom.get("roomURL"));
				return conference;
			}
			
		}
		return null;
		// 老版本代码，以防万一，下个版本可删除
		/*Map<String, Object> map = new HashMap<String, Object>();
		map.put("i", conference.getConferenceCode());
		PackerUtil packerUtil = new PackerUtil();
		packerUtil.packBody("v1:AddRoomRequest", map);
		String data = packerUtil.xDoc.getDocument().asXML();
		String xmlStr = WebServiceUtils
				.HttpClientForEsb("http://guoan.byshang.cn/services/v1_1/VidyoPortalAdminService", data, "addRoom");
		Document dom = DocumentHelper.parseText(xmlStr);
		Element root = dom.getRootElement();
		Element Body = root.element("Body");
		Element AddRoomResponse = Body.element("AddRoomResponse");
		String OK = "";
		if (AddRoomResponse != null) {
			OK = AddRoomResponse.element("OK").getText();
		}
		if ("OK".equals(OK)) {
			// 查询新创建的房间
			PackerUtil packerUtil1 = new PackerUtil();
			packerUtil1.packBody3("v1:GetRoomsRequest", map);
			String data1 = packerUtil1.xDoc.getDocument().asXML();

			String xmlStr1 = WebServiceUtils.HttpClientForEsb(
					"http://guoan.byshang.cn/services/v1_1/VidyoPortalAdminService", data1, "getRooms");
			Document dom1 = DocumentHelper.parseText(xmlStr1);
			
			Element root1 = dom1.getRootElement();
			Element Body1 = root1.element("Body");
			Element AddRoomResponse1 = Body1.element("GetRoomsResponse");
			Element room = AddRoomResponse1.element("room");
			String roomID = room.element("roomID").getText();
			Element RoomMode = room.element("RoomMode");

			String roomURL = RoomMode.element("roomURL").getText();
			String roomPIN = RoomMode.element("roomPIN").getText();
			String url = StringEscapeUtils.unescapeXml(roomURL);
			conference.setConferenceId(Integer.parseInt(roomID));
			conference.setConferencePin(roomPIN);
			conference.setConferenceUrl(url);
		}
		return conference;*/
	}

	/**
	 * 
	
	  * @Title: createConferenceCode
	
	  * @Description: 创建6～8位随机数字加字符串
	
	  * @param @return    
	
	  * @return String 
	
	  * @throws
	 */
	@Override
	public String createConferenceCode() {
		String code = RandomCharAndCode.createConferenceCode();
		List<Conference> conference = conferenceRepository.findByConferenceCode(code);

		Pattern pattern1 = Pattern.compile("[0-9]*");
		Matcher isNum = pattern1.matcher(code);
		Pattern pattern2 = Pattern.compile("[a-zA-Z]*");
		Matcher isLetter = pattern2.matcher(code);

		if (conference != null && conference.size() > 0) {
			return createConferenceCode();
		} else if (isNum.matches()) {
			return createConferenceCode();
		} else if (isLetter.matches()) {
			return createConferenceCode();
		} else {
			return code;
		}
	}

	/**
	 * 
	
	  * @Title: findConferences
	
	  * @Description: 根据用户id查找会议室列表
	
	  * @param @param uid
	  * @param @return    
	
	  * @return List<Conference> 
	
	  * @throws
	 */
	@Override
	public List<Conference> findConferences(String uid) {
		List<ConferenceUser> conferenceUsers = conferenceUserRepository.findByUidOrderByLastModifyTimeDesc(uid);
		List<Conference> conferences = new ArrayList<>();
		if (conferenceUsers != null && conferenceUsers.size() >0) {
			for (ConferenceUser conferenceUser : conferenceUsers) {
				Conference conference = conferenceRepository.findOne(conferenceUser.getCid());
				if (conference != null) {
					conference.setCreateTime(conferenceUser.getLastModifyTime());
					conferences.add(conference);
				}
			}
		}
		return conferences;
	}
	
	/**
	 * 
	
	  * @Title: searchConference
	
	  * @Description: 根据conferenceCode 搜索会议室
	
	  * @param @param code
	  * @param @return    
	
	  * @return Result 
	
	  * @throws
	 */
	@Override
	public Result searchConference(String code) {
		Result result = new Result();
		List<Conference> cons = conferenceRepository.findByConferenceCode(code);
		if (cons != null && cons.size() > 0) {
			Conference con = cons.get(0);
			ConferenceVO conferenceVO = new ConferenceVO();
			BeanUtils.copyProperties(con, conferenceVO);
			result.setKey("success");
			result.setValue(conferenceVO);
			return result;
		} 
		result.setKey("error");
		result.setValue(null);
		return result;
	}

	/**
	 * 
	
	  * @Title: conferenceDetail
	
	  * @Description: 获取会议室详情
	
	  * @param @param id
	  * @param @return    
	
	  * @return Conference 
	
	  * @throws
	 */
	@Override
	public Conference conferenceDetail(String id) {
		Conference conference = conferenceRepository.findOne(id);
		if (conference != null) {
			List<ConferenceRemind> conferenceReminds = conferenceRemindRepository.findByConferenceId(id);
			if (conferenceReminds != null && conferenceReminds.size() >0) {
				ConferenceRemind conferenceRemind = conferenceReminds.get(0);
				conference.setIsSwitch(conferenceRemind.getIsSwitch());
			} else {
				conference.setIsSwitch(0);
			}
			User user = userRepository.findOne(conference.getCreateId());
			if (user != null) {
				conference.setCreateName(user.getNickname());
			}
		}
		
		
		return conference;
	}
	
	/**
	 * 
	
	  * @Title: exchangeManager
	
	  * @Description: 更换管理员
	
	  * @param @param uid
	  * @param @param id
	  * @param @param managerId
	  * @param @return    
	
	  * @return Result 
	
	  * @throws
	 */
	@Transactional
	@Override
	public Result exchangeManager(String uid, String cid, String managerId) {
		Result result = new Result();
		Conference conference = conferenceRepository.findOne(cid);
		if (conference != null &&! conference.getManageId().equals(managerId)) {
			result.setKey("error");
			result.setValue("权限不足");
			return result;
		}
		// 更换管理员
		conferenceRepository.updateManager(uid, cid);
		// 更新操作时间
		updateLastModifyTime(cid, uid);
		/*ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(uid, cid);
		if (conferenceUser != null) {
			conferenceUser.setLastModifyTime(new Date());
			conferenceUserRepository.save(conferenceUser);
		}*/
		result.setKey("success");
		result.setValue("操作成功");
		return result;
	}
	

	/**
	 * 
	    * @Title: removeConference
	    * @Description: 删除会议室 传入会议室ID 查找会议室 把会议室信息传入历史会议室表 把参会人员传入历史会议室列表 之后将会议室跟参会人员删除
	    * @param @param id
	    * @param @return
	    * @param @throws Exception
	    * @return Result
	    * @throws
	 */
	@Override
	@Transactional
	public Result removeConference(String id) throws Exception {
		Result result = new Result();
		Conference conference = conferenceRepository.findOne(id);
		result = removeVidyo(conference.getConferenceId().toString());
		HistoryConference hc = new HistoryConference();
		BeanUtils.copyProperties(conference, hc);
		hc.setDeleteTime(new Date());
		historyConferenceRepository.save(hc);// 保存到历史会议室列表
		List<ConferenceUser> conferenceUsers = conferenceUserRepository.findByCid(id);
		List<HistoryConferenceUser> hcUsers = new ArrayList<>();
		for (ConferenceUser conferenceUser : conferenceUsers) {
			HistoryConferenceUser hcUser = new HistoryConferenceUser();
			BeanUtils.copyProperties(conferenceUser, hcUser);
			hcUser.setDeleteTime(new Date());
			hcUsers.add(hcUser);
		}
		historyConferenceUserRepository.save(hcUsers); // 保存到历史参会人员列表
		conferenceUserRepository.delete(conferenceUsers); // 删除参会人员
		conferenceRepository.delete(id); // 删除会议室
		
		
		return result;
	}
	
	/**
	 * 调用vidyo接口删除 vidyo的会议室
	 */
	@Override
	public Result removeVidyo(String roomId) throws Exception{
		Result result = new Result();
		Map<String, String> elementBody = new HashMap<>();
		elementBody.put("roomID", roomId);
		boolean flag = VidyoWebServiceAPI.deleteRoom(elementBody);
		if (flag) {
			result.setKey("success");
			result.setValue("删除成功");
		}else {
			result.setKey("error");
			result.setValue("删除失败");
		}
		/*	Map<String, Object> map = new HashMap<String, Object>();
		PackerUtil packerUtil2 = new PackerUtil();
		map.put("roomID", roomId);
		packerUtil2.packBody1("v1:DeleteRoomRequest", map);
		String data2 = packerUtil2.xDoc.getDocument().asXML();
		System.out.println(data2);
		// 调用webservice/删除room接口
		String xmlStr = WebServiceUtils
				.HttpClientForEsb("http://guoan.byshang.cn/services/v1_1/VidyoPortalAdminService", data2, "deleteRoom");

		System.out.println(xmlStr);
		Document dom = DocumentHelper.parseText(xmlStr);
		Element root = dom.getRootElement();
		Element Body = root.element("Body");
		Element AddRoomResponse = Body.element("DeleteRoomResponse");
		String OK = AddRoomResponse.element("OK").getText();
		if ("OK".equals(OK)) {
			result.setKey("success");
			result.setValue("删除成功");
		} else {
			result.setKey("error");
			result.setValue("删除失败");
		}*/

		return result;
	}

	/**
	 * 
	
	  * @Title: getParticipants
	
	  * @Description: 获取参与会议室的人
	
	  * @param @param id
	  * @param @param uid
	  * @param @return    
	
	  * @return Result 
	
	  * @throws
	 */
	@Override
	public Result getParticipants(String cid, String uid) {
		Result result = new Result();
		List<ConferenceUserVO> conferenceUserVOs = new ArrayList<ConferenceUserVO>();
		List<ConferenceUser> conUsers = conferenceUserRepository.findByCid(cid);
		List<String> userIdList  = conUsers.stream().map(ConferenceUser::getUid).collect(Collectors.toList());
		// 查询备注
		List<Object[]> note = contactsDao.findUserIdAndFriendRemarks(userIdList, uid);
	
		
		for (ConferenceUser conferenceUser : conUsers) {
			User user = userRepository.findOne(conferenceUser.getUid());
			ConferenceUserVO conferenceUserVO = new ConferenceUserVO();
			if (user != null) {
				BeanUtils.copyProperties(user, conferenceUserVO);
				JoinConference joinConference = joinConferenceRepository.findByCidAndUid(cid, user.getId());
				if (joinConference != null) {
					conferenceUserVO.setIsJoin(joinConference.getIsJoin());
				} else {
					conferenceUserVO.setIsJoin(0);
				}
			}
			
			
			conferenceUserVOs.add(conferenceUserVO);
		}
		
		
		/*List<User> users = userRepository.findAll(userIdList);
		for (User user : users) {
			ConferenceUserVO conferenceUserVO = new ConferenceUserVO();
			BeanUtils.copyProperties(user, conferenceUserVO);
			JoinConference joinConference = joinConferenceRepository.findByCidAndUid(cid, user.getId());
			if (joinConference != null) {
				conferenceUserVO.setIsJoin(joinConference.getIsJoin());
			} else {
				conferenceUserVO.setIsJoin(0);
			}
			
			conferenceUserVOs.add(conferenceUserVO);
		}*/
		// 查询好友备注
		for (Object[] objects : note) {
			for (ConferenceUserVO user : conferenceUserVOs) {
				if (objects[0].equals(user.getId())) {
					user.setNickname((String)objects[1]);
				}
			}
			
			
		}
		result.setKey("success");
		result.setValue(conferenceUserVOs);
		return result;
	}
	/**
	 * 
	
	  * @Title: addParticipant
	
	  * @Description: 添加参会人员
	
	  * @param @param cid 会议室id
	  * @param @param uids 被邀请参会人员id数组(ios在接收数组时需要特殊处理uid.replaceAll("\"", ""))
	  * @param @param uid 创建者id
	  * @param @return    
	
	  * @return Result 
	
	  * @throws
	 */
	@Transactional
	@Override
	public Result addParticipant(String cid, String[] uids, String uuid) {
		Result result = new Result();
		ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(uuid, cid);
		if (conferenceUser == null) {
			result.setKey("error");
			result.setValue("您不在此会议中，无权限邀请参会人员");
			return result;
		}
		if (uids != null) {
			Conference conference = conferenceRepository.findOne(cid);
			if (conference == null) {
				result.setKey("error");
				result.setValue("该会议室不存在");
				return result;
			}
			if ((conference.getPeople_all() - conference.getPeople_num()) < uids.length) {
				result.setKey("error");
				result.setValue("超过人员上限");
				return result;
			} 
			if (conference.getType() ==2 && conference.getPeople_num() ==2) {
				conference.setType(1);//俩人拉会变成普通会议
			}
			conference.setPeople_num(conference.getPeople_num() + uids.length);
			conferenceRepository.save(conference);
			
			// 更新操作时间
			updateLastModifyTime(cid, uuid);
			
			for (String uid : uids) {
				ConferenceUser conUser = conferenceUserRepository.findByUidAndCid(uid.replaceAll("\"", ""), cid);
				if (conUser == null) {
					ConferenceUser newConUser = new ConferenceUser();
					newConUser.setCid(cid);
					newConUser.setUid(uid.replaceAll("\"", ""));
					newConUser.setLastModifyTime(new Date());
					conferenceUserRepository.save(newConUser);
				}
				
			}
			// 推送消息
			saveMessage(cid, uids, uuid);
			
		}
		
		result.setKey("success");
		result.setValue("邀请成功");

		
		return result;
	}
	
	/**
	 * 
	    * @Title: removeParticipant
	    * @Description: 踢人接口
	    * @param @param cid
	    * @param @param uids
	    * @param @param id
	    * @param @return
	    * @param @throws Exception
	    * @return Result
	    * @throws
	 */
	@Override
	@Transactional
	public Result removeParticipant(String cid, String[] uids, String managerId) throws Exception{
		Result result = new Result();
		Conference conference = conferenceRepository.findOne(cid);
		if (conference == null) {
			result.setKey("error");
			result.setValue("会议室不存在");
			return result;
		}
		if (conference != null &&! conference.getManageId().equals(managerId)) {
			result.setKey("error");
			result.setValue("权限不足");
			return result;
		}
		/*JPushRestAPI jPushRestAPI = new JPushRestAPI();
		List<PushSwitch> list = pushSwitchRepository.findAll();
		PushSwitch pushSwitch  = list.get(0);
		if (pushSwitch.getIsSwitch() == 0) {
			jPushRestAPI.setApns_production(false);
		}
		List<ConferenceUser> conferenceUsers = conferenceUserRepository.findByCid(cid);
		for (ConferenceUser conferenceUser2 : conferenceUsers) {
			User user = userRepository.findOne(conferenceUser2.getUid());
			if (user != null) {
				jPushRestAPI.SendPush("", "12", null, "", jPushRestAPI.jsonDataByOneAlias(user.getUsername()));
				
			}
			
		}*/
		for (String uid : uids) {
			JoinConference con = joinConferenceRepository.findByCidAndUid(cid, uid.replaceAll("\"", ""));
			boolean flag = true;
			if (con != null) {
				Map<String, String> elementBody = new HashMap<>();
				elementBody.put("conferenceID", conference.getConferenceId().toString());
				elementBody.put("participantID", con.getParticipantid());
				// 移除人员
				boolean resultFlag = VidyoWebServiceAPI.leaveConference(elementBody);
				if (! resultFlag) {
					flag = false;
				}
				/*String xmlStr = WebServiceUtils.leaveConference(conference.getConferenceId().toString(), con.getParticipantid());
				Document dom = DocumentHelper.parseText(xmlStr);
				Element root = dom.getRootElement();
				Element Body = root.element("Body");
				Element AddRoomResponse = Body.element("LeaveConferenceResponse");
				if (AddRoomResponse != null) {
					String OK = AddRoomResponse.element("OK").getText();
					if (! "OK".equals(OK)) {
						flag = false;
					}
				}*/
			}
			ConferenceUser cu = conferenceUserRepository.findByUidAndCid(uid.replaceAll("\"", ""), cid);
			if (cu != null) {
				conference.setPeople_num(conference.getPeople_num() - 1);
				conferenceRepository.save(conference);
				HistoryConferenceUser hcu = new HistoryConferenceUser();
				BeanUtils.copyProperties(cu, hcu);
				hcu.setDeleteTime(new Date());
				historyConferenceUserRepository.save(hcu);
				conferenceUserRepository.delete(cu);
				if (flag) {
					result.setKey("success");
					result.setValue("移除成功");
				} else {
					result.setKey("error");
					result.setValue("移除失败");
				}
				
			}
		}
		updateLastModifyTime(cid, managerId);
		
		return result;
	}
	
	/**
	 * @throws DocumentException 
	 * 
	
	  * @Title: joinConference
	
	  * @Description: 加入会议室后调用，获取vidyo分配的participant
	
	  * @param @param uid
	  * @param @param cid
	  * @param @return    
	
	  * @return Result 
	
	  * @throws
	 */
	@Transactional
	@Override
	public Result joinConference(String uid, String cid, Integer channel) throws DocumentException {
		Result result = new Result();
		// 添加入会记录
		JoinConferenceRecord conferenceRecord =  new JoinConferenceRecord();
		conferenceRecord.setJoinTime(new Date());
		conferenceRecord.setUid(uid);
		conferenceRecord.setCid(cid);
		if (channel != null) {
			conferenceRecord.setChannel(channel);
		}
		joinConferenceRecordRepository.save(conferenceRecord);
		
		JoinConference joinConference = joinConferenceRepository.findByCidAndUid(cid, uid);
		// 非首次入会，加入次数增加
		if (joinConference != null) {
			joinConference.setJoinCount(joinConference.getJoinCount()+1);
		} else {
			// 首次入会
			joinConference = new JoinConference();
			joinConference.setCid(cid);
			joinConference.setUid(uid);
			joinConference.setJoinCount(1);
			joinConference.setTotalTime(0);
			joinConference.setJoinCount(0);
			joinConference.setLeaveTime(new Date());
		}
		joinConference.setJoinTime(new Date());
		joinConference.setIsJoin(1);
		Conference conference = conferenceRepository.findOne(cid);
		Map<String, String> elementBody = new HashMap<>();
		if (conference != null) {
			joinConference.setConferenceid(conference.getConferenceId().toString());
			// 查询参会人员
			elementBody.put("roomID", conference.getConferenceId().toString());
			String resultXml = VidyoWebServiceAPI.getParticipants(elementBody);
			Map<String, Object> mapResult = VidyoWebServiceAPI.xmlParserMap(resultXml, VidyoConstant.GET_PARTICIPANTS_RESPONSE);
			int total = Integer.parseInt((String)mapResult.get("total"));
			// 如果人数大于0则继续解析
			if (total > 0) {
				List<Map<String, String>> listMap = (List<Map<String, String>>)mapResult.get("listReult");
				for (Map<String, String> map : listMap) {
					String displayName = map.get("displayName");
					displayName = (displayName.length() > 32) ? displayName.substring(displayName.length() -32) : displayName;
					if (uid.equals(displayName)) {
						joinConference.setParticipantid(map.get("participantID"));
					}
				}
				
			}
		}
		
		/*if (conference != null) {
			joinConference.setConferenceid(conference.getConferenceId().toString());
			xmlStr = WebServiceUtils.getParticipants(conference.getConferenceId().toString());
		}
		if (xmlStr != null &&! "".equals(xmlStr)) {
			Pattern pattern1 = Pattern.compile("<ns1:participantID>([^<>]*)</ns1:participantID>");//匹配participantID
			Matcher matcher1 = pattern1.matcher(xmlStr);
			Pattern pattern2 = Pattern.compile("<ns1:displayName>([^<>]*)</ns1:displayName>");//匹配displayName
			Matcher matcher2 = pattern2.matcher(xmlStr);
			while (matcher1.find() && matcher2.find()) {
				String str = matcher2.group(1);
				if (str.length() > 32) {
					String displayName = str.substring(str.length() -32);
					System.out.println("--------------------"+ displayName +"----------------");
					if (uid.equals(displayName)) {
						joinConference.setParticipantid(matcher1.group(1));
						System.out.println("--------------------"+ matcher1.group(1) +"----------------");
					}
				}
				
			}
			
		}*/
		JoinConference isSave = joinConferenceRepository.save(joinConference);
		if (isSave != null) {
			result.setKey("success");
			result.setValue("加入成功");
			User user = userRepository.findOne(uid);
			if (user != null) {
				user.setJoin_video_num(user.getJoin_video_num() + 1);
				userRepository.save(user);
			}
			updateLastModifyTime(cid, uid);
			/*ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(uid, cid);
			if (conferenceUser != null) {
				conferenceUser.setLastModifyTime(new Date());
				conferenceUserRepository.save(conferenceUser);
			}*/
			PushAPI(cid, "12", null);
			/*JPushRestAPI jPushRestAPI = new JPushRestAPI();
			List<PushSwitch> list = pushSwitchRepository.findAll();
			PushSwitch pushSwitch  = list.get(0);
			if (pushSwitch.getIsSwitch() == 0) {
				jPushRestAPI.setApns_production(false);
			}
//			jPushRestAPI.SendPush(message.getMessage(), "10", cid, "Default", jPushRestAPI.jsonDataByOneAlias(user.getUsername()));
			List<ConferenceUser> conferenceUsers = conferenceUserRepository.findByCid(cid);
			for (ConferenceUser conferenceUser : conferenceUsers) {
				User user = userRepository.findOne(conferenceUser.getUid());
				if (user != null) {
					jPushRestAPI.SendPush("", "12", null, "", jPushRestAPI.jsonDataByOneAlias(user.getUsername()));
				}
				 
			}*/
		}

		
		return result;
	}
	/**
	 * @throws DocumentException 
	 * @throws DocumentException 
	 * 
	    * @Title: updateJoinConference
	    * @Description: 更新入会出会的人员的状态
	    * @param 
	    * @return void
	    * @throws
	 */
	@Override
	@Transactional
	public void updateJoinConference() throws DocumentException {
		// 查询状态为入会的人员
		List<JoinConference> joinConferences = joinConferenceRepository.findByIsJoin(1);
		if (joinConferences != null && joinConferences.size() >0) {
			// 遍历查询是否仍在vidyo会议中
			for (JoinConference joinConference : joinConferences) {
				Map<String, String> elementBody = new HashMap<>();
				elementBody.put("roomID", joinConference.getConferenceid());
				String xmlResult = VidyoWebServiceAPI.getParticipants(elementBody);
				Map<String, Object> mapResult = VidyoWebServiceAPI.xmlParserMap(xmlResult, VidyoConstant.GET_PARTICIPANTS_RESPONSE);
				int total = Integer.parseInt((String)mapResult.get("total"));
				User user = userRepository.findOne(joinConference.getUid());
				// 如果人数大于0则继续解析
				if (total > 0) {
					List<Map<String, String>> listMap = (List<Map<String, String>>)mapResult.get("listReult");
					boolean flag = false;
					for (Map<String, String> map : listMap) {
						String displayName = map.get("displayName");
						displayName = (displayName.length() > 32) ? displayName.substring(displayName.length() -32) : displayName;
						if (joinConference.getUid().equals(displayName)) {
							// 查到为true
							flag = true;
						}
					}
					// 没有查到代表已经离会，更高状态和时间
					if (flag == false) {
						joinConference.setIsJoin(0);
						joinConference.setLeaveTime(new Date());
						if (joinConference.getLeaveTime() != null && joinConference.getJoinTime() !=  null) {
							Long time = joinConference.getLeaveTime().getTime() - joinConference.getJoinTime().getTime();
							Long m = time / (1000 * 60);
							Long s = time / 1000;
//							Long s =  (joinConference.getLeaveTime().getTime() - joinConference.getJoinTime().getTime()) /(1000 *60);
							joinConference.setTotalTime(joinConference.getTotalTime() + m.intValue());
							if (user != null) {
								user.setTotal_join_meeting_time(user.getTotal_join_meeting_time() + s);
							}
						}
						PushAPI(joinConference.getCid(), "12", null);
						
					}
					// 会议中没有人，已经离会
				} else {
					joinConference.setIsJoin(0);
					joinConference.setLeaveTime(new Date());
					if (joinConference.getLeaveTime() != null && joinConference.getJoinTime() !=  null) {
						Long time = joinConference.getLeaveTime().getTime() - joinConference.getJoinTime().getTime();
						Long m = time / (1000 * 60);
						Long s = time / 1000;
//						Long s =  (joinConference.getLeaveTime().getTime() - joinConference.getJoinTime().getTime()) /(1000 *60);
						joinConference.setTotalTime(joinConference.getTotalTime() + m.intValue());
						if (user != null) {
							user.setTotal_join_meeting_time(user.getTotal_join_meeting_time() + s);
						}	
					}
					PushAPI(joinConference.getCid(), "12", null);
				}
				/*String xmlStr = WebServiceUtils.getParticipants(joinConference.getConferenceid());
				if (xmlStr.contains("ns1:Entity")) {
					Pattern displayNamePattern = Pattern.compile("<ns1:displayName>([^<>]*)</ns1:displayName>");//匹配displayName
					Matcher displayNameMatcher = displayNamePattern.matcher(xmlStr);
					boolean flag = false;
					while (displayNameMatcher.find()) {
						if (displayNameMatcher.group(1).length() >32) {
							String displayName = displayNameMatcher.group(1).substring(displayNameMatcher.group(1).length() -32);
							if(joinConference.getUid().equals(displayName)) {
								flag = true;
							}
						}
						
					}
					if (flag == false) {
						joinConference.setIsJoin(0);
						joinConference.setLeaveTime(new Date());
						if (joinConference.getLeaveTime() != null && joinConference.getJoinTime() !=  null) {
							Long s =  (joinConference.getLeaveTime().getTime() - joinConference.getJoinTime().getTime()) /(1000 *60);
							joinConference.setTotalTime(joinConference.getTotalTime() + s.intValue());	
						}
						PushAPI(joinConference.getCid(), "12", null);
						
					}
				} else {
					joinConference.setIsJoin(0);
					joinConference.setLeaveTime(new Date());
					if (joinConference.getLeaveTime() != null && joinConference.getJoinTime() !=  null) {
						Long s =  (joinConference.getLeaveTime().getTime() - joinConference.getJoinTime().getTime()) /(1000 *60);
						joinConference.setTotalTime(joinConference.getTotalTime() + s.intValue());	
					}
					PushAPI(joinConference.getCid(), "12", null);
					
				}*/
				joinConferenceRepository.save(joinConference);
				userRepository.save(user);
			}
			
		}
		
	}
	/**
	 * 
	    * @Title: beginRemind
	    * @Description: 设置参会提醒
	    * @param @param conferenceId 会议室id
	    * @param @param isSwitch 开关 0关 1开
	    * @param @param beginTime 开始时间
	    * @param @param firstTime 提醒时间
	    * @param @param secondTime 废弃字段
	    * @param @param id 参会提醒的业务id
	    * @param @return
	    * @param @throws Exception
	    * @return Result
	    * @throws
	 */
	@Transactional
	@Override
	public Result beginRemind(String conferenceId, Integer isSwitch,String beginTime,String firstTime,String secondTime, String id) throws Exception{
		ConferenceRemind conferenceRemind = null;
		Result result = new Result();
		if (isSwitch == 1) {
			Date begin = new Date(Long.valueOf(beginTime));
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");//设置日期格式
			String endStr = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
			Date end = df.parse(endStr);
			if (begin.getTime() < end.getTime()) {
				result.setKey("error");
				result.setValue("会议时间不能小于当前时间");
				return result;
			}
		}
		

		if (id != null) {
			conferenceRemind = conferenceRemindRepository.findOne(id);
		}

		if (conferenceRemind == null) {
			conferenceRemind = new ConferenceRemind();
			conferenceRemind.setConferenceId(conferenceId);
		}
		conferenceRemind.setBeginTime(new Date(Long.valueOf(beginTime)));
		conferenceRemind.setIsSwitch(isSwitch);
		conferenceRemind.setIsPush(0);
		conferenceRemind.setRemindTime(Long.valueOf(firstTime));
		conferenceRemind.setPushTime(new Date(Long.valueOf(beginTime) - Long.valueOf(firstTime)));
		conferenceRemindRepository.save(conferenceRemind);
		
		
		result.setKey("success");
		result.setValue("保存成功");
		Conference conference = conferenceRepository.findOne(conferenceId);
		if (conference != null) {
			ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(conference.getManageId(), conferenceId);
			if (conferenceUser != null) {
				conferenceUser.setLastModifyTime(new Date());
				conferenceUserRepository.save(conferenceUser);
			}
		}
		
		
		return result;
	}
	
	/**
	 * @throws DocumentException 
	 * 
	    * @Title: iosLeave
	    * @Description: ios切掉应用vidyo有bug，调用踢人，推出会议室
	    * @param @param cid
	    * @param @param uid
	    * @param @return
	    * @return Result
	    * @throws
	 */
	@Override
	public Result iosLeave(String cid, String uid) throws DocumentException {
		Result result = new Result();
		// 查询参会信息
		JoinConference joinConference = joinConferenceRepository.findByCidAndUid(cid, uid);
		if (joinConference != null) {
			Map<String, String> elementBody = new HashMap<>();
			elementBody.put("conferenceID", joinConference.getConferenceid());
			elementBody.put("participantID", joinConference.getParticipantid());
			boolean flag = VidyoWebServiceAPI.leaveConference(elementBody);
			if (flag) {
				result.setKey("success");
				result.setValue("移除成功");
				return result;
			}
		}
		/*if (con != null) {
			String xmlStr = WebServiceUtils.leaveConference(con.getConferenceid(), con.getParticipantid());
			Document dom = null;
			try {
				dom = DocumentHelper.parseText(xmlStr);
			} catch (DocumentException e) {
				e.printStackTrace();
			}
			Element root = dom.getRootElement();
			Element Body = root.element("Body");
			Element AddRoomResponse = Body.element("LeaveConferenceResponse");
			String OK = AddRoomResponse.element("OK").getText();
			if ("OK".equals(OK)) {
				result.setKey("success");
				result.setValue("移除成功");
				return result;
			}
			
		}*/
		result.setKey("error");
		result.setValue("移除失败");
		return result;
	}
	
	/**
	 * 
	    * @Title: enterConference
	    * @Description: 加入会议室
	    * @param @param cid
	    * @param @param uid
	    * @param @return
	    * @return Result
	    * @throws
	 */
	@Transactional
	@Override
	public Result enterConference(String cid, String uid) {
		Result result = new Result();
		ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(uid, cid);
		if (conferenceUser != null) {
			result.setKey("success");
			result.setValue("已经在当前会议室中");
			return result;
		}
		Conference conference = conferenceRepository.findOne(cid);
		if (conference != null) {
			if (conference.getPeople_num() >= conference.getPeople_all()) {
				result.setKey("errror");
				result.setValue("会议室人员已满");
				return result;
			} else {
				// 更改会议室状态
				if (conference.getType() ==2 && conference.getPeople_num() ==2) {
					conference.setType(1);
				}
				conference.setPeople_num(conference.getPeople_num() + 1);
				conferenceRepository.save(conference);
				
			}
			ConferenceUser conUser = new ConferenceUser();
			conUser.setCid(cid);
			conUser.setUid(uid);
			conUser.setLastModifyTime(new Date());
			conferenceUserRepository.save(conUser);
			result.setKey("success");
			result.setValue("加入会议室成功");
			
			JPushRestAPI jPushRestAPI = new JPushRestAPI();
			List<PushSwitch> list = pushSwitchRepository.findAll();
			PushSwitch pushSwitch  = list.get(0);
			if (pushSwitch.getIsSwitch() == 0) {
				jPushRestAPI.setApns_production(false);
			}
	
			List<ConferenceUser> conferenceUsers = conferenceUserRepository.findByCid(cid);
			for (ConferenceUser conferenceUser2 : conferenceUsers) {
				User user = userRepository.findOne(conferenceUser2.getUid());
				if (user != null) {
					jPushRestAPI.SendPush("", "12", null, "", jPushRestAPI.jsonDataByOneAlias(user.getUsername()));
					
				}
				
			}
			
			return result;
		}
		result.setKey("errror");
		result.setValue("会议室不存在");
		return result;
	}
	
	/**
	 * 
	    * @Title: checkJoin
	    * @Description: 检查是否可以进入会议
	    * @param @param uid
	    * @param @param cid
	    * @param @return
	    * @return Result
	    * @throws
	 */
	@Override
	public Result checkJoin(String uid, String cid) {
		Result result = new Result();
		Conference conference = conferenceRepository.findOne(cid);
		if (conference == null) {
			result.setKey("error");
			result.setValue("会议室不存在");
			return result;
		}
		User user = userRepository.findOne(uid);
		if (user == null) {
			result.setKey("success");
			result.setValue("用户不存在");
			return result;
		}
		List<JoinConference> conferences = joinConferenceRepository.findByUid(uid);
		if (conferences != null && conferences.size() >0) {
			for (JoinConference joinConference : conferences) {
				if (joinConference.getIsJoin() == 1) {
					result.setKey("error");
					result.setValue("当前账户已在会议中，请先退出会议后尝试再次参会。");
					return result;
				}
			}
		}
		result.setKey("success");
		result.setValue("可以入会");
		return result;
	}
	/**
	 * 
	
	  * @Title: push
	
	  * @Description: 推送消息
	
	  * @param @param message
	  * @param @param cid    
	
	  * @return void 
	
	  * @throws
	 */
	@Override
	public void push(Message message, String cid) {
		JPushRestAPI jPushRestAPI = new JPushRestAPI();
		List<PushSwitch> list = pushSwitchRepository.findAll();
		PushSwitch pushSwitch  = list.get(0);
		if (pushSwitch.getIsSwitch() == 0) {
			jPushRestAPI.setApns_production(false);
		}
		User user = userRepository.findOne(message.getUserid());
		String username = "";
		if (user != null) {
			username = user.getUsername();
		}
		jPushRestAPI.SendPush(message.getMessage(), "11", null, "Default", jPushRestAPI.jsonDataByOneAlias(username));
		
	}
	
	/**
	 * 
	
	  * @Title: saveMessage
	
	  * @Description: 保存消息
	
	  * @param @param cid
	  * @param @param uids
	  * @param @param uid    
	
	  * @return void 
	
	  * @throws
	 */
	@Transactional
	@Override
	public void saveMessage(String cid, String[] uids, String uid) {
		Conference con = conferenceRepository.findOne(cid);
		String name = "";
		if (con != null) {
			name = con.getName();
		}
		String content = "";
		User user = userRepository.findOne(uid);
		if (user != null) {
			content += user.getNickname();
		}
		content += "邀请您参加 "+ name +" 会议";
		MessagePush messagePush = new MessagePush();
		messagePush.setContent(content);
		messagePush.setTitle("邀请入会通知");
		messagePush.setSendTime(new Date());
		messagePush.setType(3);
		messagePush.setMesKey("11");
		messagePush.setMesValue(cid);
		MessagePush afterSave = messagePushRepository.save(messagePush);
		
		for (String id : uids) {
			if (id.replaceAll("\"", "").equals(uid)) {
				continue;
			}
			User ur = userRepository.findOne(id);
			String username = "";
			if (ur != null) {
				username = ur.getUsername();
			}
			MessagePushUser messagePushUser = new MessagePushUser();
			messagePushUser.setMessageId(afterSave.getId());
			messagePushUser.setUsername(username);
			messagePushUserRepository.save(messagePushUser);
			Message message = new Message();
			message.setTitle("系统消息");
			message.setMessage(content);
			message.setMesType(5);
			message.setSendWay(3);
			message.setCreatetime(new Date());
			message.setIsRead(0);
			message.setCreateId(uid);
			message.setUserid(id.replaceAll("\"", ""));
			Message saveUpdate = messageRepository.save(message);
			// 推送消息
			push(saveUpdate, cid);
		}
	}
	/**
	 * 
	    * @Title: autoRemind
	    * @Description: 参会提醒
	    * @param @throws Exception
	    * @return void
	    * @throws
	 */
	@Transactional
	@Override
	public void autoRemind() throws Exception{
		JPushRestAPI jPushRestAPI = new JPushRestAPI();
		List<PushSwitch> list = pushSwitchRepository.findAll();
		PushSwitch pushSwitch  = list.get(0);
		if (pushSwitch.getIsSwitch() == 0) {
			jPushRestAPI.setApns_production(false);
		}
		List<ConferenceRemind> conferenceReminds = conferenceRemindRepository.findByIsPush(0);
		for (ConferenceRemind conferenceRemind : conferenceReminds) {
			if (conferenceRemind.getIsSwitch() == 1) {
				Date date = new Date();
				if (date.getTime() >= conferenceRemind.getPushTime().getTime()) {
					String cid = conferenceRemind.getConferenceId();
					MessagePush messagePush = new MessagePush();
					String content = "";
					Conference conference = conferenceRepository.findOne(cid);
					
					SimpleDateFormat df = new SimpleDateFormat("yyy年MM月dd日 HH时mm分");//设置日期格式
					String time = df.format(conferenceRemind.getBeginTime());
					if (conference != null) {
						content = "您有会议将在"+time+"开始，请注意准时参会，会议室名称为 “"+conference.getName()+"”";
					}else {
						content = "您有会议将在"+time+"开始，请注意准时参会。";
					}
					messagePush.setContent(content);
					messagePush.setTitle("会议开始通知");
					messagePush.setSendTime(new Date());
					messagePush.setType(3);
					messagePush.setMesKey("10");
					messagePush.setMesValue(cid);
					MessagePush afterSave = messagePushRepository.save(messagePush);
					List<ConferenceUser> conferenceUsers  = conferenceUserRepository.findByCid(cid);
					for (ConferenceUser conferenceUser : conferenceUsers) {
						User user = userRepository.findOne(conferenceUser.getUid());
						MessagePushUser messagePushUser = new MessagePushUser();
						messagePushUser.setMessageId(afterSave.getId());
						messagePushUser.setUsername(user.getUsername());
						messagePushUserRepository.save(messagePushUser);
						Message message = new Message();
						message.setTitle("系统消息");
						message.setMessage(content);
						message.setMesType(6);
						message.setSendWay(3);
						message.setCreatetime(new Date());
						message.setIsRead(0);
						message.setUserid(conferenceUser.getUid());
						message.setDetailId(cid);
						messageRepository.save(message);
						jPushRestAPI.SendPush(message.getMessage(), "10", null, "Default", jPushRestAPI.jsonDataByOneAlias(user.getUsername()));
//						push.jiguangPush(user.getUsername(), "10", afterSave.getContent(), afterSave.getTitle(), cid);
						SendCode.sendMessage(user.getUsername(), message.getMessage());
//						push.jiguangPush(username, mesType, message, title, url)
					}
					conferenceRemind.setIsPush(1);
					conferenceRemindRepository.save(conferenceRemind);
			
					
				}
				
			}
			
		}
		
	}
	/**
	 * 
	    * @Title: leaveConference
	    * @Description: 离开会议室
	    * @param @param uid
	    * @param @param cid
	    * @param @return
	    * @param @throws Exception
	    * @return Result
	    * @throws
	 */
	@Transactional
	@Override
	public Result leaveConference(String uid, String cid) throws Exception {
		Result result = new Result();
		Conference conference = conferenceRepository.findOne(cid);
		if (conference == null) {
			result.setKey("error");
			result.setValue("不存在此会议室");
			return result;
		}
		JPushRestAPI jPushRestAPI = new JPushRestAPI();
		List<PushSwitch> list = pushSwitchRepository.findAll();
		PushSwitch pushSwitch  = list.get(0);
		if (pushSwitch.getIsSwitch() == 0) {
			jPushRestAPI.setApns_production(false);
		}
		
		ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(uid, cid);
		if (conferenceUser != null) {
			// 会议室人员减1
			conference.setPeople_num(conference.getPeople_num() -1);
			
			HistoryConferenceUser hcUser = new HistoryConferenceUser();
			BeanUtils.copyProperties(conferenceUser, hcUser);
			hcUser.setDeleteTime(new Date());
			// 保存历史表
			historyConferenceUserRepository.save(hcUser);
			conferenceUserRepository.delete(conferenceUser);

			List<ConferenceUser> conferenceUsers = conferenceUserRepository.findByCid(cid);
			// 如果会议室中没有人，解散会议室
			if (conferenceUsers != null && conferenceUsers.size() == 0) {
				// 移除会议室摄像头
				List<ConferenceCameras> conferenceCameras = conferenceCamerasRepository.findByCidAndIsJoinOrderByJoinTimeDesc(cid, 1);
				if (conferenceCameras != null && conferenceCameras.size() >0) {
					ConferenceCameras cameras = conferenceCameras.get(0);
					leaveConferenceCameras(cameras.getScid());
				}
				// 删除vidyo会议室
				removeConference(cid);
			}else {
				// 如果管理员离开会议室，第一个成员成为管理员
				if (conference.getManageId().equals(uid)) {
					conference.setManageId(conferenceUsers.get(0).getUid());
					
					
				}
				conferenceRepository.save(conference);
			}
			// 推送更新详情。后期会修改
			UpdateModel model = new UpdateModel();
			model.setManagerId(conference.getManageId());
			List<ConferenceUser> conUsers = conferenceUserRepository.findByCid(cid);
			for (ConferenceUser conferenceUser2 : conUsers) {
				User user = userRepository.findOne(conferenceUser2.getUid());
				if (user != null) {
					jPushRestAPI.SendPush("", "12", model, "", jPushRestAPI.jsonDataByOneAlias(user.getUsername()));
					
				}
				
			}
			
			result.setKey("success");
			result.setValue("离会成功");
			
			return result;
		}
		result.setKey("error");
		result.setValue("不在此会议中");
		return result;
	}
	/**
	 * 
	    * @Title: updateConferenceCode
	    * @Description: 更新会议室编号
	    * @param @param cid
	    * @param @param uid
	    * @param @return
	    * @return Result
	    * @throws
	 */
	@Override
	public Result updateConferenceCode(String cid, String uid) {
		Result result = new Result();
		Conference conference = conferenceRepository.findOne(cid);
		if (conference != null) {
			if (! conference.getManageId().equals(uid)) {
				result.setKey("error");
				result.setValue("权限不足");
				return result;
			}
			// 创建编号
			conference.setConferenceCode(createConferenceCode());
			Conference conference2 = conferenceRepository.save(conference);
			if (conference2 != null) {
				// 更新操作时间
				updateLastModifyTime(cid, uid);
				result.setKey("success");
				result.setValue(conference2.getConferenceCode());
				// 下面为复制的推送逻辑。后期可用长连接。
				UpdateModel updateModel = new UpdateModel();
				updateModel.setConferenceCode(conference2.getConferenceCode());
			//	PushAPI(cid, "13", updateModel);
				JPushRestAPI jPushRestAPI = new JPushRestAPI();
				List<PushSwitch> list = pushSwitchRepository.findAll();
				PushSwitch pushSwitch  = list.get(0);
				if (pushSwitch.getIsSwitch() == 0) {
					jPushRestAPI.setApns_production(false);
				}
			//	UpdateModel updateModel = new UpdateModel();
			//	updateModel.setConferenceCode(conference2.getConferenceCode());
				List<ConferenceUser> conferenceUsers = conferenceUserRepository.findByCid(cid);
				for (ConferenceUser conferenceUser2 : conferenceUsers) {
					if (conferenceUser2.getUid().equals(uid)) {
						continue;
					}
					User user = userRepository.findOne(conferenceUser2.getUid());
					if (user != null) {
						jPushRestAPI.SendPush("", "13", updateModel, "", jPushRestAPI.jsonDataByOneAlias(user.getUsername()));
						
					}
					
				}
			}
			
			
		}
		return result;
	}
	/**
	 * 
	    * @Title: updateName
	    * @Description: 更新会议室名称
	    * @param @param uid
	    * @param @param cid
	    * @param @param name
	    * @param @return
	    * @return Result
	    * @throws
	 */
	@Transactional
	@Override
	public Result updateName(String uid, String cid, String name) {
		Result result = new Result();
		Conference conference = conferenceRepository.findOne(cid);
		if (conference != null) {
			if (! conference.getManageId().equals(uid)) {
				result.setKey("error");
				result.setValue("权限不足");
				return result;
			}
			conference.setName(name);
			conferenceRepository.save(conference);
			result.setKey("success");
			result.setValue("更改成功");
			// 更新操作会议室时间
			updateLastModifyTime(cid, uid);
		}
		UpdateModel updateModel = new UpdateModel();
		updateModel.setName(name);
		PushAPI(cid, "13", updateModel);
		

		return result;
	}
	
	/**
	 * 
	    * @Title: updateTopic
	    * @Description: 更新主题
	    * @param @param uid
	    * @param @param cid
	    * @param @param topic
	    * @param @return
	    * @return Result
	    * @throws
	 */
	@Transactional
	@Override
	public Result updateTopic(String uid, String cid, String topic) {
		Result result = new Result();
		Conference conference = conferenceRepository.findOne(cid);
		if (conference != null) {
			if (! conference.getManageId().equals(uid)) {
				result.setKey("error");
				result.setValue("权限不足");
				return result;
			}
			conference.setTopic(topic);
			conferenceRepository.save(conference);
			result.setKey("success");
			result.setValue("更改成功");
			// 更新操作会议室时间
			updateLastModifyTime(cid, uid);
		}
		UpdateModel updateModel = new UpdateModel();
		updateModel.setTopic(topic);
		PushAPI(cid, "13", updateModel);

		return result;
	}
	/**
	 * 
	    * @Title: findRemindTime
	    * @Description: 查询参会提醒
	    * @param @param cid
	    * @param @return
	    * @return Result
	    * @throws
	 */
	@Override
	public Result findRemindTime(String cid) {
		Result result = new Result();
		List<ConferenceRemind> conferenceReminds = conferenceRemindRepository.findByConferenceId(cid);
		result.setKey("success");
		result.setValue(conferenceReminds);
		return result;
	}
	
	/**
	 * 
	    * @Title: findConferene
	    * @Description: PC端查找会议室
	    * @param @param conferenceId
	    * @param @return
	    * @return Result
	    * @throws
	 */
	@Override
	public Result findConferene(String conferenceId) {
		Result result = new Result();
		List<Conference> conferences = conferenceRepository.findByConferenceCode(conferenceId);
		if (conferences != null && conferences.size() >0) {
			result.setKey("success");
			result.setValue(conferences.get(0));
			return result;
		}
		result.setKey("error");
		result.setValue(null);
	
		return result;
	}
	
	/**
	 * 
	    * @Title: recentlyConference
	    * @Description: PC端会议室列表
	    * @param @param uid
	    * @param @param page
	    * @param @param size
	    * @param @return
	    * @return Map<String,Object>
	    * @throws
	 */
	@Override
	public Map<String, Object> recentlyConference(String uid, Integer page, Integer size) {
		Map<String, Object> map = new HashMap<>();
		Pageable pageAble = new PageRequest(page, size, Sort.Direction.DESC,"lastModifyTime");
		Page<ConferenceUser> conferenceUsers = conferenceUserRepository.findByUidOrderByLastModifyTimeDesc(uid, pageAble);
		ArrayList<Conference> conferences = new ArrayList<>();
		for (ConferenceUser conferenceUser : conferenceUsers) {
			Conference conference = conferenceRepository.findOne(conferenceUser.getCid());
			if (conference != null) {
				conference.setCreateTime(conferenceUser.getLastModifyTime());
				conferences.add(conference);
			}
		}
		map.put("total", conferenceUsers.getTotalPages());
		map.put("conferenceList", conferences);
		/*String jpql= "select * from conference where id in (select cid from conference_user where uid =:uid) order by create_time desc";
		Query query = manager.createNativeQuery(jpql, Conference.class);
		query.setParameter("uid", uid);
		map.put("total", query.getResultList().size());
		query.setFirstResult(page * size);
		query.setMaxResults(size);
		map.put("conferenceList", query.getResultList());*/
		return map;
	}
	
	/**
	 * 
	    * @Title: toEnterConference
	    * @Description: PC加入会议室
	    * @param @param uid
	    * @param @param cid
	    * @param @return
	    * @return Result
	    * @throws
	 */
	@Transactional
	@Override
	public Result toEnterConference(String uid, String cid) {
		Result result = new Result();
		ConferenceUser conferenUser = conferenceUserRepository.findByUidAndCid(uid, cid);
		if (conferenUser == null) {
			ConferenceUser conUser = new ConferenceUser();
			conUser.setCid(cid);
			conUser.setUid(uid);
			conUser.setLastModifyTime(new Date());
			conferenceUserRepository.save(conUser);
			Conference conference = conferenceRepository.findOne(cid);
			if (conference != null) {
				conference.setPeople_num(conference.getPeople_num() + 1);
				conferenceRepository.save(conference);
			}
		}
		
		List<ConferenceUserVO> users = new ArrayList<ConferenceUserVO>();
		List<ConferenceUser> conUsers = conferenceUserRepository.findByCid(cid);
		for (ConferenceUser conferenceUser : conUsers) {
			ConferenceUserVO conferenceUserVO = new ConferenceUserVO();
			User user = userRepository.findOne(conferenceUser.getUid());
			BeanUtils.copyProperties(user, conferenceUserVO);
			/*JoinConference joinConference = joinConferenceRepository.findByCidAndUid(conferenceUser.getCid(), conferenceUser.getUid());
			if (joinConference != null) {
				conferenceUserVO.setIsJoin(joinConference.getIsJoin());
			} else {
				conferenceUserVO.setIsJoin(0);
			}*/
			
			users.add(conferenceUserVO);
		}
		result.setKey("success");
		result.setValue(users);
		return result;
	}

	/**
	 * 
	    * @Title: updateUserVideoDate
	    * @Description: 每一小时更新用户使用会议室情况
	    * @param @return
	    * @return Result
	    * @throws
	 */
	@Override
	public Result updateUserVideoDate() {
		Result result = new Result();
		
		/*List<JoinConference> joinConferences = joinConferenceRepository.findAll();
		for (JoinConference joinConference : joinConferences) {
			User user = userRepository.findOne(joinConference.getUid());
			user.setJoin_video_num(user.getJoin_video_num() + joinConference.getJoinCount());
			user.setTotal_join_meeting_time(user.getTotal_join_meeting_time() + Long.valueOf(joinConference.getTotalTime()));
			userRepository.save(user);
		}*/
		result.setKey("success");
		result.setValue("更新成功");
		return result;
	}
	/**
	 * 
	    * @Title: PushAPI
	    * @Description: 封装了一个推送
	    * @param @param cid
	    * @param @param mes_type
	    * @param @param object
	    * @return void
	    * @throws
	 */
	@Override
	public void PushAPI(String cid,String mes_type, Object object) {
		JPushRestAPI jPushRestAPI = new JPushRestAPI();
		List<PushSwitch> list = pushSwitchRepository.findAll();
		PushSwitch pushSwitch  = list.get(0);
		if (pushSwitch.getIsSwitch() == 0) {
			jPushRestAPI.setApns_production(false);
		}
		List<ConferenceUser> conferenceUser = conferenceUserRepository.findByCid(cid);
		List<String> uids = conferenceUser.stream().map(ConferenceUser::getUid).collect(Collectors.toList());
		List<User> users = userRepository.findAll(uids);
		List<String> usernames = users.stream().map(User::getUsername).collect(Collectors.toList());
		jPushRestAPI.SendPush("", mes_type,object, "", jPushRestAPI.jsonDataByManyAlias(usernames));
		
		
	}

	@Override
	public Result inviteToConference(String conferenceID, String invite) throws Exception {
		Result result = new Result();
		Map<String, Object> resMap = new HashMap<>();
		resMap.put("conferenceID", conferenceID);
		resMap.put("invite", invite);
		
		PackerUtil packerUtil = new PackerUtil();
		packerUtil.packBody6("v1:InviteToConferenceRequest", resMap);
		String RequestXml = packerUtil.xDoc.getDocument().asXML();
		String ResponseXml = WebServiceUtils
				.HttpClientForEsb("http://guoan.byshang.cn/services/v1_1/VidyoPortalAdminService", RequestXml, "inviteToConference");
		
		Document dom = DocumentHelper.parseText(ResponseXml);
		Element root = dom.getRootElement();
		Element Body = root.element("Body");
		Element inviteToConferenceResponse = Body.element("InviteToConferenceResponse");
		String OK = "";
		if (inviteToConferenceResponse != null) {
			OK = inviteToConferenceResponse.element("OK").getText();
			if ("OK".equals(OK)) {
				result.setKey("success");
				result.setValue("呼叫成功");
			} else {
				result.setKey("error");
				result.setValue("呼叫失败");
			}
		}
		return result;
	}

	@Override
	public Result JoininviteToConference(String conferenceID, String invite) throws Exception {
		String jpql = "SELECT c FROM Conference c ORDER BY c.createTime DESC";
		Query query = manager.createQuery(jpql);
		List<Conference> conferences = query.getResultList();
		if (conferenceID != null && "".equals(conferenceID)) {
			if (conferences != null && conferences.size() >0) {
				Conference conference = conferences.get(0);
				if (conference != null) {
					conferenceID = String.valueOf(conference.getConferenceId());
				}
			}
			
		}
		if (invite != null && "".equals(invite)) {
			invite = "0302@10.45.10.7";
		}
		Result result = new Result();
		Map<String, Object> resMap = new HashMap<>();
		resMap.put("conferenceID", conferenceID);
		resMap.put("invite", invite);
		
		PackerUtil packerUtil = new PackerUtil();
		packerUtil.packBody6("v1:InviteToConferenceRequest", resMap);
		String RequestXml = packerUtil.xDoc.getDocument().asXML();
		String ResponseXml = WebServiceUtils
				.HttpClientForEsb("http://guoan.byshang.cn/services/v1_1/VidyoPortalAdminService", RequestXml, "inviteToConference");
		
		Document dom = DocumentHelper.parseText(ResponseXml);
		Element root = dom.getRootElement();
		Element Body = root.element("Body");
		Element inviteToConferenceResponse = Body.element("InviteToConferenceResponse");
		String OK = "";
		if (inviteToConferenceResponse != null) {
			OK = inviteToConferenceResponse.element("OK").getText();
			if ("OK".equals(OK)) {
				result.setKey("success");
				result.setValue("呼叫成功");
			} else {
				result.setKey("error");
				result.setValue("呼叫失败");
			}
		}
		return result;
	}

	@Override
	public Result leaveinviteToConference(String conferenceID, String participantID) throws Exception{
		Result result = new Result();
		String jpql = "SELECT c FROM Conference c ORDER BY c.createTime DESC";
		Query query = manager.createQuery(jpql);
		List<Conference> conferences = query.getResultList();
		if (conferenceID != null && "".equals(conferenceID)) {
			if (conferences != null && conferences.size() >0) {
				Conference conference = conferences.get(0);
				if (conference != null) {
					conferenceID = String.valueOf(conference.getConferenceId());
				}
			}
			
		}
		if (participantID != null && "".equals(participantID)) {
			String xmlStr = WebServiceUtils.getParticipants(conferenceID);
			if (xmlStr.contains("ns1:Entity")) {
				Pattern pattern1 = Pattern.compile("<ns1:participantID>([^<>]*)</ns1:participantID>");//匹配participantID
				Matcher matcher1 = pattern1.matcher(xmlStr);
				Pattern pattern2 = Pattern.compile("<ns1:EntityType>Legacy</ns1:EntityType>");//匹配displayName
				Matcher matcher2 = pattern2.matcher(xmlStr);
				while (matcher1.find() && matcher2.find()) {
					participantID = matcher1.group(1);
				}
				
			}
		}
		
		String xmlStr = WebServiceUtils.leaveConference(conferenceID, participantID);
		Document dom = DocumentHelper.parseText(xmlStr);
		Element root = dom.getRootElement();
		Element Body = root.element("Body");
		Element AddRoomResponse = Body.element("LeaveConferenceResponse");
		if (AddRoomResponse != null) {
			String OK = AddRoomResponse.element("OK").getText();
			if ("OK".equals(OK)) {
				result.setKey("success");
				result.setValue("移除成功");
			} else {
				result.setKey("error");
				result.setValue("移除失败");
			}
		}
		return result;
	}
	
	/**
	 * 在门店使用详情页面呼叫摄像头
	 * conferenceCode 6～8会议室id
	 * storeCamerasId 门店摄像头id
	 */
	@Transactional
	@Override
	public Result joinConferenceCameras(String conferenceCode, String storeCamerasId) throws Exception {
		Result result = new Result();
		if (conferenceCode != null &&! "".equals(conferenceCode)) {
			List<Conference> conferences = conferenceRepository.findByConferenceCode(conferenceCode);
			if (conferences != null && conferences.size() >0) {
				Conference conference = conferences.get(0);
				if (conference != null) {
					StoreCameras cameras = storeCamerasRepository.getNoDealCamers(storeCamerasId);
					if (cameras != null && cameras.getStatus() == 1) {
						result.setKey("error");
						result.setValue("该会议终端正在使用中");
					}else {
						ConferenceCameras conferenceCameras = new ConferenceCameras();
						conferenceCameras.setIsJoin(1);
						conferenceCameras.setCid(conference.getId());
						conferenceCameras.setJoinTime(new Date());
						if (cameras != null) {
							cameras.setStatus(1);
							conferenceCameras.setScid(cameras.getId());
						}
						Result returnResult = inviteToConference(String.valueOf(conference.getConferenceId()), cameras.getMeetingRoomId() + "@" + cameras.getIp());
						if (returnResult != null && "success".equals(returnResult.getKey())) {
							cameras.setMeetingName(conference.getName());
							cameras.setMeetingId(conference.getId());
							conferenceCamerasRepository.save(conferenceCameras);
							storeCamerasRepository.save(cameras);
							result.setKey("success");
							result.setValue("已成功加入会议室");
							List<String> userids = cameraDao.getUserIdByCameraId(storeCamerasId);
							if (userids != null && userids.size() >0) {
								String userId = userids.get(0);
								
								ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(userId, conference.getId());
								if (conferenceUser != null) {
									conferenceUser.setLastModifyTime(new Date());
									conferenceUserRepository.save(conferenceUser);
								}
							}
							
							
						} else {
							result.setKey("error");
							result.setValue("加入会议室失败，请稍后再试");
						}
					}
				}
				PushAPI(conference.getId(), "12", null);
			} else {
				result.setKey("error");
				result.setValue("会议室不存在");
			}
		} else {
			result.setKey("error");
			result.setValue("会议室ID不能为空");
		}
		
		return result;
	}
	/**
	 * 在门店使用详情页面推出摄像头
	 * storeCamerasId 摄像头id
	 * 
	 */
	@Transactional
	@Override
	public Result leaveConferenceCameras(String storeCamerasId) throws Exception{
		Result result = new Result();
		List<ConferenceCameras> conferenceCameras = conferenceCamerasRepository.findByScidAndIsJoin(storeCamerasId, 1);
		if (conferenceCameras != null && conferenceCameras.size() >0) {
			ConferenceCameras cameras = conferenceCameras.get(0);
			if (cameras != null) {
				Conference conference = conferenceRepository.findOne(cameras.getCid());
				if (conference != null) {
					StoreCameras storeCameras = storeCamerasRepository.findOne(storeCamerasId);
					if (storeCameras != null) {
						storeCameras.setStatus(0);
						storeCameras.setMeetingId(null);
						storeCameras.setMeetingName(null);
						String xmlStr = WebServiceUtils.getParticipants(String.valueOf(conference.getConferenceId()));
						if (xmlStr.contains("ns1:Entity")) {
							Pattern pattern1 = Pattern.compile("<ns1:participantID>([^<>]*)</ns1:participantID>");//匹配participantID
							Matcher matcher1 = pattern1.matcher(xmlStr);
							Pattern pattern2 = Pattern.compile("<ns1:displayName>("+storeCameras.getMeetingRoomId()+"@"+storeCameras.getIp()+")</ns1:displayName>");//匹配displayName
							Matcher matcher2 = pattern2.matcher(xmlStr);
							while (matcher1.find() && matcher2.find()) {
								cameras.setParticipantID(matcher1.group(1));
							}
							
						}
					}
					
					cameras.setLeaveTime(new Date());
					cameras.setIsJoin(0);
					if (cameras.getParticipantID() != null) {
						Result returnResult = leaveConferenceVidyo(String.valueOf(conference.getConferenceId()), cameras.getParticipantID());
						if (returnResult != null && "success".equals(returnResult.getKey())) {
							conferenceCamerasRepository.save(cameras);
							storeCamerasRepository.save(storeCameras);
							result.setKey("success");
							result.setValue("成功退出会议室");
							List<String> userids = cameraDao.getUserIdByCameraId(storeCamerasId);
							if (userids != null && userids.size() >0) {
								String userId = userids.get(0);
								
								ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(userId, conference.getId());
								if (conferenceUser != null) {
									conferenceUser.setLastModifyTime(new Date());
									conferenceUserRepository.save(conferenceUser);
								}
							}
							
						}else {
							result.setKey("error");
							result.setValue("退出会议室失败，请稍后再试");
						}
					}else {
						leaveConferenceCameras(storeCamerasId);
					}
					PushAPI(conference.getId(), "12", null);
				}
				
				
			}
		}
		return result;
	}
	
	@Override
	public Result leaveConferenceVidyo(String conferenceID, String participantID) throws Exception{
		Result result = new Result();
		String xmlStr = WebServiceUtils.leaveConference(conferenceID, participantID);
		Document dom = DocumentHelper.parseText(xmlStr);
		Element root = dom.getRootElement();
		Element Body = root.element("Body");
		Element AddRoomResponse = Body.element("LeaveConferenceResponse");
		if (AddRoomResponse != null) {
			String OK = AddRoomResponse.element("OK").getText();
			if ("OK".equals(OK)) {
				result.setKey("success");
				result.setValue("移除成功");
			} else {
				result.setKey("error");
				result.setValue("移除失败");
			}
		}
		return result;
	}
	
	@Transactional
	@Override
	public Result createAndJoinConferenceCameras(String cid, String[] storeCamerasId) throws Exception {
		Result result = new Result();
		Conference conference = conferenceRepository.findOne(cid);
		
		if (conference != null) {
			if (storeCamerasId != null && storeCamerasId.length >0) {
				List<ConferenceCameras> cameras = new ArrayList<>();
				List<String> names = new ArrayList<>();
				
				for (String scid : storeCamerasId) {
					StoreCameras storeCameras = storeCamerasRepository.findOne(scid.replaceAll("\"", ""));
					
					if (storeCameras != null) {
						
						storeCameras.setStatus(1);
						ConferenceCameras conferenceCameras = new ConferenceCameras();
						conferenceCameras.setCid(conference.getId());
						conferenceCameras.setIsJoin(1);
						conferenceCameras.setJoinTime(new Date());
						conferenceCameras.setScid(scid.replaceAll("\"", ""));
						cameras.add(conferenceCameras);
						
						Result returnResult = inviteToConference(String.valueOf(conference.getConferenceId()), storeCameras.getMeetingRoomId() + "@" + storeCameras.getIp());
						
						if (returnResult != null && "success".equals(returnResult.getKey())) {
							List<String> userids = cameraDao.getUserIdByCameraId(scid.replaceAll("\"", ""));
							if (userids != null && userids.size() >0) {
								String userId = userids.get(0);
								ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(userId, conference.getId());
								if (conferenceUser != null) {
									conferenceUser.setLastModifyTime(new Date());
									conferenceUserRepository.save(conferenceUser);
								}
							}
							storeCameras.setMeetingName(conference.getName());
							storeCameras.setMeetingId(conference.getId());
							storeCamerasRepository.save(storeCameras);
						}else if (returnResult != null && "error".equals(returnResult.getKey())) {
							names.add(storeCameras.getChineseName());
						}
					}
					
				}
				
				if (names != null && names.size() >0) {
					StringBuffer strbuffer = new StringBuffer();
					strbuffer.append("设备名称为：");
					for (String name : names) {
						strbuffer.append(name + "，");
					}
					strbuffer.replace(strbuffer.length()-1, strbuffer.length(), "的设备呼叫失败，请稍后再试");
					result.setKey("error");
					result.setValue(strbuffer.toString());
				} else {
					conferenceCamerasRepository.save(cameras);
					result.setKey("success");
					result.setValue("呼叫成功");
					
					
				}
				
			}
		}

		return result;
	}
	/**
	 * 
	    * @Title: detailLeaveConferenceCamera
	    * @Description: 详情页管理员移除设备
	    * @param @param cid
	    * @param @param storeCamerasId
	    * @param @return
	    * @param @throws Exception
	    * @return Result
	    * @throws
	 */
	@Transactional
	@Override
	public Result detailLeaveConferenceCamera(String cid, String[] storeCamerasId) throws Exception {
		Result result = new Result();
		Conference conference = conferenceRepository.findOne(cid);
		if (conference != null) {
			if (storeCamerasId != null && storeCamerasId.length >0) {
				List<ConferenceCameras> saveCameras = new ArrayList<>();
				List<String> names = new ArrayList<>();
				for (String scid : storeCamerasId) {
					List<ConferenceCameras> conferenceCameras = conferenceCamerasRepository.findByScidAndIsJoin(scid.replaceAll("\"", ""), 1);//查询已经加入会议室的摄像头
					if (conferenceCameras != null && conferenceCameras.size() >0) {
						ConferenceCameras cameras = conferenceCameras.get(0);//查询加入会议室的摄像头
						if (cameras != null) {
							StoreCameras storeCameras = storeCamerasRepository.findOne(scid.replaceAll("\"", "")); //查询门店摄像头
							if (storeCameras != null) {
								storeCameras.setStatus(0);
								storeCameras.setMeetingId(null);
								storeCameras.setMeetingName(null);
								String xmlStr = WebServiceUtils.getParticipants(String.valueOf(conference.getConferenceId()));
								if (xmlStr.contains("ns1:Entity")) {
									Pattern pattern1 = Pattern.compile("<ns1:participantID>([^<>]*)</ns1:participantID>");//匹配participantID
									Matcher matcher1 = pattern1.matcher(xmlStr);
									Pattern pattern2 = Pattern.compile("<ns1:displayName>("+storeCameras.getMeetingRoomId()+"@"+storeCameras.getIp()+")</ns1:displayName>");//匹配displayName
									Matcher matcher2 = pattern2.matcher(xmlStr);
									while (matcher1.find() && matcher2.find()) {
										cameras.setParticipantID(matcher1.group(1));//取出ParticipantID
									}
									
								}
							}
							cameras.setLeaveTime(new Date());
							cameras.setIsJoin(0);
							saveCameras.add(cameras);
							if (cameras.getParticipantID() != null) {
								Result returnResult = leaveConferenceVidyo(String.valueOf(conference.getConferenceId()), cameras.getParticipantID());//移除摄像头
								if (returnResult != null && "success".equals(returnResult.getKey())) {
									List<String> userids = cameraDao.getUserIdByCameraId(scid.replaceAll("\"", ""));
									if (userids != null && userids.size() >0) {
										User user = userRepository.findOne(userids.get(0));
										if (user != null) {
											MessagePush messagePush = new MessagePush();
											messagePush.setContent("国安社区双井店的会议设备已被管理员从【"+conference.getName()+"】移除");
											messagePush.setTitle("系统信息");
											messagePush.setSendTime(new Date());
											messagePush.setType(3);
											messagePush.setMesKey("11");
											messagePush.setMesValue("摄像头");
											MessagePush afterSave = messagePushRepository.save(messagePush);
											MessagePushUser messagePushUser = new MessagePushUser();
											messagePushUser.setMessageId(afterSave.getId());
											messagePushUser.setUsername(user.getUsername());
											messagePushUserRepository.save(messagePushUser);
											Message message = new Message();
											message.setTitle("系统消息");
											message.setMessage("国安社区双井店的会议设备已被管理员从【"+conference.getName()+"】移除");
											message.setMesType(5);
											message.setSendWay(3);
											message.setCreatetime(new Date());
											message.setIsRead(0);
//											message.setCreateId(uid);
											message.setUserid(user.getId());
											Message saveUpdate = messageRepository.save(message);
											push(saveUpdate, cid);
										}
									}
									storeCamerasRepository.save(storeCameras);
									
								}else {
									names.add(storeCameras.getChineseName());
								}
							}
						}
						
					}
				}

				if (names != null && names.size() >0) {
					StringBuffer strbuffer = new StringBuffer();
					strbuffer.append("设备名称为：");
					for (String name : names) {
						strbuffer.append(name + "，");
					}
					strbuffer.replace(strbuffer.length()-1, strbuffer.length(), "的设备移除失败，请稍后再试");
					result.setKey("error");
					result.setValue(strbuffer.toString());
				} else {
					conferenceCamerasRepository.save(saveCameras);
					result.setKey("success");
					result.setValue("移除成功");
					ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(conference.getManageId(), cid);
					if (conferenceUser != null) {
						conferenceUser.setLastModifyTime(new Date());
						conferenceUserRepository.save(conferenceUser);
					}
				}
			}
		}
		return result;
	}
	/**
	 * 获取会议详情页的摄像头列表
	 * cid 会议室id
	 */
	@Override
	public Result getConferenceCamera(String cid) throws Exception {
		Result result = new Result();
		Conference conference = conferenceRepository.findOne(cid);//根据会议室ID查询会议室
		if (conference != null) {
			//根据会议室ID和是否已经加入查找会议室摄像头，并且安卓加入时间倒序查找
			List<ConferenceCameras> conferenceCameras = conferenceCamerasRepository.findByCidAndIsJoinOrderByJoinTimeDesc(cid, 1);
			List<StoreCameras> cameras = new ArrayList<>();
			if (conferenceCameras != null && conferenceCameras.size() >0) {
				for (ConferenceCameras conferenceCamera : conferenceCameras) {
					cameras.add(storeCamerasRepository.findOne(conferenceCamera.getScid()));
				}
			} 
			result.setKey("success");
			result.setValue(cameras);
			
		}
		return result;
	}
	
	/**
	 * 
	
	  * @Title: checkType
	
	  * @Description: 根据创建者id，和被拉会人id,判断会议室类型
	
	  * @param @param uid 创建者id
	  * @param @param joinUid 被拉会人id
	  * @param @return    
	
	  * @return String 
	
	  * @throws
	 */
	@Override
	public String checkType(String uid, String joinUid) {
		List<ConferenceUser> conferenceUsers = conferenceUserRepository.findByUid(uid);
		List<String> cids = conferenceUsers.stream().map(ConferenceUser::getCid).collect(Collectors.toList());
		List<Conference> conferences = conferenceRepository.findAll(cids);
		List<Conference> cons = conferences.stream().filter(c -> c.getType() == 2).collect(Collectors.toList());
		for (Conference conference : cons) {
			ConferenceUser conUser = conferenceUserRepository.findByUidAndCid(joinUid, conference.getId());
			if (conUser != null) {
				return conference.getId();
			}
		}
		
		return null;
	}
	/**
	 * 
	
	  * @Title: updateLastModifyTime
	
	  * @Description: 更新对会议室进行操作的时间
	
	  * @param @param cid
	  * @param @param uid    
	
	  * @return void 
	
	  * @throws
	 */
	@Transactional
	@Override
	public void updateLastModifyTime(String cid, String uid) {
		ConferenceUser conferenceUser = conferenceUserRepository.findByUidAndCid(uid, cid);
		if (conferenceUser != null) {
			conferenceUser.setLastModifyTime(new Date());
			conferenceUserRepository.save(conferenceUser);
		}
		
		
	}

	
}
